<template>
  <el-row :gutter="6">
    <el-col :span="24" class="col-flex">
      <el-col class="breadcrumb-container">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/main' }">信息管理</el-breadcrumb-item>
          <el-breadcrumb-item>公告详情</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
      <el-col class="maincont-container">
        <my-tableX
          v-loading="listloading"
          element-loading-text="正在删除......"
          element-loading-spinner="el-icon-loading"
          tableHeight="340px"
          v-show="showindex"
          @dataView="viewData"
          @dataEdit="editData"
          @dataDelete="deleteData"
          @dataAdd="addNewAnnounce"
          :tableData="announceData"
          :configs="configs"
        ></my-tableX>
        <div
          v-show="!showindex"
          class="data-form"
          v-loading="loading"
          element-loading-text="正在提交......"
          element-loading-spinner="el-icon-loading"
        >
          <div>
            <h5>{{operationType}}</h5>
          </div>
          <el-form
            size="small"
            :rules="rules"
            style
            ref="announceForm"
            :model="announceInfo"
            label-width="100px"
          >
            <el-form-item label="公告标题" prop="notice_title">
              <el-input :disabled="onlyview" v-model="announceInfo.notice_title"></el-input>
            </el-form-item>
            <el-form-item label="公告类型" prop="notice_type">
              <el-select :disabled="onlyview" v-model="announceInfo.notice_type" placeholder="请选择">
                <el-option label="会议通知" value="会议通知"></el-option>
                <el-option label="月报" value="月报"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="公告内容" prop="notice_content">
              <el-input :disabled="onlyview" type="textarea" v-model="announceInfo.notice_content"></el-input>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-input disabled v-model="announceInfo.create_time"></el-input>
            </el-form-item>
            <el-form-item label="创建人">
              <el-input v-model="announceInfo.create_by" disabled></el-input>
            </el-form-item>
            <!-- <el-form-item label="文件列表">
              <el-input v-model="announceInfo.projectEngineer"></el-input>
            </el-form-item>-->
            <el-form-item label="附件列表">
              <el-upload
                :on-change="handleChange"
                :disabled="onlyview"
                class="upload-demo"
                ref="upload"
                action="1"
                :limit="5"
                :accept="filetype"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :file-list="fileList"
                :before-upload="beforeUpload"
                :http-request="uploadSectionFile"
              >
                <!-- <el-button v-if="!onlyview" slot="trigger" size="small" type="primary">选取文件</el-button> -->
                <!-- <el-button
                  v-if="!onlyview"
                  style="margin-left: 10px;"
                  size="small"
                  type="success"
                  @click="submitUpload"
                >上传到服务器</el-button> -->
                <el-button v-if="!onlyview" slot="trigger" size="small" type="primary">选取文件</el-button>
                <div v-if="!onlyview" slot="tip" class="el-upload__tip">上传图片、文档文件，最多上传5个</div>
              </el-upload>
            </el-form-item>
            <el-form-item v-if="operationType=='新增公告'" label="查看权限">
              <el-checkbox-group style="text-align:left" v-model="announceInfo.role">
                <el-checkbox :label="itm.id" :key="itm.id" v-for="itm in roletypes">{{itm.roleName}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <el-form-item style="text-align:right">
              <el-button v-if="!onlyview" :disabled="onlyview" type="primary" @click="onSubmit">提交</el-button>
              <el-button @click="onCancel">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-col>
  </el-row>
</template>

<script>
import myTableX from "../../../../components/base/tableX";
import { formatDate } from "../../../../utils/date";
import { random } from "../../../../utils/random";
import httpfile from "../../../../api/file/index";

import FILE_TYPE from "@/config/file.type.config";

export default {
  components: { myTableX },
  inject: ["reload"],
  created() {
    let query = this.$route.query;
    let isquery = query != null && JSON.stringify(query) != "{}";
    if (isquery) {
      this.viewData(this.$route.query);
    }

    this.$api.announce
      .list({
        roleid: this.$store.state.m_user.userInfo.roleId,
        subject_id: this.$store.state.projectInfo.projectName
      })
      .then(res => {
        if (res.code == 200) {
          this.announceData = res.data;
          this.$message("加载公告信息成功");
        } else {
          this.$message.error("加载公告信息失败:" + res.msg);
        }
      })
      .catch(err => {
        this.$message.error("加载公告信息失败");
      });
  },

  computed: {
    roletypes() {
      return this.$store.state.m_user.roles;
    }
  },

  data() {
    return {
      filetype: FILE_TYPE.Announce,
      onlyview: true,
      rules: {
        notice_title: [
          { required: true, message: "请输入公告标题", trigger: "blur" }
        ],
        notice_type: [
          { required: true, message: "请选择公告类型", trigger: "blur" }
        ],
        projetId: [
          { required: true, trigger: "blur", message: "请输入工程编号" }
        ],
        projectName: [
          { required: true, trigger: "blur", message: "请输入工程名称" }
        ]
      },

      operationType: "",
      showindex: true,
      announceInfo: {},
      announceData: [],
      configs: {
        columns: [
          { field: "notice_title", name: "公告标题" },
          { field: "notice_type", name: "公告类型" },
          { field: "notice_content", name: "公告内容" },
          { field: "create_time", name: "创建时间" },
          { field: "create_by", name: "创建人" }
        ],
        operationCol: {
          show: true,
          view: true,
          edit: this.$store.state.m_user.userInfo.roleId <= 3,
          delete: this.$store.state.m_user.userInfo.roleId <= 3,
          download: false
        },
        showFilterRow: {
          show: true
        },
        operationBtn: {
          show: true,
          add: this.$store.state.m_user.userInfo.roleId <= 3,
          output: false
        }
      },
      fileList: [],
      loading: false,
      listloading: false
    };
  },
  methods: {
    /**
     * @description: 上传文件之前的操作，进行格式和大小的检验
     * @param {type}
     * @return:
     */
    beforeUpload(file) {
      console.log("before up");
      console.log(file);
      let testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      if (this.filetype.indexOf("." + testmsg.toLowerCase()) < 0) {
        this.$message({
          message: "上传文件格式不符合要求：" + testmsg,
          type: "warning"
        });
        return false;
      }
      return true;
    },

    /**
     * @description: 上传文件的操作
     * @param {type}
     * @return:
     */
    uploadSectionFile(params) {
      const uid = params.file.uid;
      console.log(params);

      // ##修改##
      let URL = window.URL || window.webkitURL;
      let url = URL.createObjectURL(params.file);

      let keyname = formatDate(new Date(), "yyyyMMddhhmmss") + random();
      // ##修改##

      const fileData = new FormData();
      fileData.append("file", params.file);
      const query = {
        path:
          "/" +
          this.$store.state.projectInfo.projectName +
          "/公告/" +
          keyname +
          params.file.name
      };

      const config = {
        headers: {
          "Content-Type": "multipart/form-data",
          token: window.sessionStorage.getItem("token")
        },
        // 这一段代码解决进度条不显示的问题，属于 axios 的使用知识。具体可以看文末的参考链接。
        onUploadProgress: progressEvent => {
          const percentCompleted = Math.floor(
            (progressEvent.loaded * 100) / progressEvent.total
          );
          params.onProgress({ percent: percentCompleted });
        }
      };

      httpfile.upload(query, config, fileData).then(res => {
        if (res.status == 200) {
          // ##修改##
          this.fileList.push({
            url: url,
            name: params.file.name,
            realname: keyname + params.file.name
          });
          // ##修改##
          params.onSuccess(res);
        }
      });
    },
    handleChange(file, filelist) {
      console.log("change list");
      console.log(filelist);
    },
    // 新增按钮
    addNewAnnounce() {
      this.showindex = false;
      this.onlyview = false;
      this.operationType = "新增公告";
      this.fileList = [];
      this.announceInfo = {
        create_time: this.getNowFormatDate(),
        create_by: this.$store.state.m_user.userInfo.user_name,
        role: [],
        subject_id: this.$store.state.projectInfo.projectName,
        path: this.$route.path
      };
    },

    //查看公告
    viewData(row) {
      if (row.path !== "" && row.path !== this.$route.path) {
        // 其他模块
        this.$router.push({
          path: row.path,
          query: { id: row.notice_id, remark: row.remark }
        });
        return;
      }

      this.operationType = "查看公告";
      this.announceInfo = {
        notice_id: row.notice_id,
        subject_id: row.subject_id,
        notice_title: row.notice_title,
        notice_type: row.notice_type,
        notice_content: row.notice_content,
        url: row.url,
        create_by: row.create_by,
        status: row.status,
        create_time: row.create_time,
        update_time: row.update_time,
        remark: row.remark,
        path: row.path
      };
      this.fileList = [];
      console.log(row);

      // ##修改##
      if (row.url != "") {
        row.url.split(";").forEach(item => {
          if (item != "") {
            let b = item.split("/");
            this.fileList.push({
              name: b[b.length - 1].slice(18),
              realname: b.slice(b.length - 1, b.length).toString(String),
              url: item
            });
          }
        });
      }
      // ##修改##

      this.showindex = false;
      this.onlyview = true;
    },

    editData(row) {
      console.log(row);
      this.operationType = "编辑公告";
      this.announceInfo = {
        notice_id: row.notice_id,
        subject_id: row.subject_id,
        notice_title: row.notice_title,
        notice_type: row.notice_type,
        notice_content: row.notice_content,
        url: row.url,
        create_by: row.create_by,
        status: row.status,
        create_time: row.create_time,
        update_time: row.update_time,
        remark: row.remark
      };
      this.fileList = [];
      if (row.url != "") {
        row.url.split(";").forEach(item => {
          if (item != "") {
            let b = item.split("/");
            this.fileList.push({
              name: b[b.length - 1].slice(18),
              realname: b.slice(b.length - 1, b.length).toString(String),
              url: item
            });
          }
        });
      }
      this.showindex = false;
      this.onlyview = false;
    },

    deleteData(row) {
      console.log(row);
      this.$confirm("此操作将永久删除该公告, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.listloading = true;
        this.$api.announce
          .delete({
            reqMap: row.notice_id
          })
          .then(res => {
            if (res.code == 200) {
              this.$api.announce
                .deleteRoleByNotice({ reqMap: row.notice_id })
                .then(res => {
                  this.listloading = false;
                  if (res.code === 200) {
                    this.$message.success("删除成功");
                    this.reload();
                  } else {
                    this.$message.error("删除失败:" + res.msg);
                  }
                })
                .catch(err => {
                  this.$message.error("删除失败:" + err);
                });
            } else {
              this.listloading = false;
              this.$message.error("删除失败:" + res.msg);
            }
          })
          .catch(err => {
            this.listloading = false;
            this.$message.error("删除失败:" + err);
          });
      });
    },

    handleRemove(file, fileList) {
      let temp = this.fileList.filter(item => {
        return item.uid != file.uid;
      });

      this.fileList = temp;
    },

    handlePreview(file) {
      console.log("remove");
      console.log(file);
      window.open(file.url);
    },

    //提交表单，包括新增和修改
    onSubmit() {
      if (this.operationType == "编辑公告") {
        this.$refs.announceForm.validate(res => {
          if (res) {
            this.$confirm("提交后不可更改，是否继续？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            })
              .then(() => {
                console.log(this.fileList);
                this.announceInfo.url = this.fileList
                  .map(item => {
                    return (
                      "/" +
                      this.$store.state.projectInfo.projectName +
                      "/公告/" +
                      item.realname // ##修改##
                    );
                  })
                  .join(";");
                console.log(this.announceInfo);
                this.announceInfo.update_time = this.getNowFormatDate();
                this.loading = true;
                this.$api.announce
                  .update(this.announceInfo)
                  .then(res => {
                    this.loading = false;
                    if (res.code == 200) {
                      this.$message.success("操作成功!");
                      this.showindex = false;
                      this.reload();
                    } else {
                      this.$message.error("操作失败!" + res.msg);
                    }
                  })
                  .catch(err => {
                    this.loading = false;
                    this.$message.error("操作失败!" + err);
                  });
              })
              .catch(() => {
                return;
              });
          }
        });
      } else {
        //新增公告
        this.$refs.announceForm.validate(res => {
          if (res) {
            if (this.announceInfo.role.length == 0) {
              // this.$alert.warning('请至少选择一个查看人')
              this.$message.warning("请至少选择一个查看人");
              console.log(this.$alert);
              return;
            }
            this.$confirm("提交后不可更改，是否继续？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            })
              .then(() => {
                this.announceInfo.url = this.fileList
                  .map(item => {
                    return (
                      "/" +
                      this.$store.state.projectInfo.projectName +
                      "/公告/" +
                      item.realname
                    );
                  })
                  .join(";");
                this.loading = true;
                let params = {};
                for (var i in this.announceInfo) {
                  params[i] = this.announceInfo[i];
                }
                params.create_time = this.getNowFormatDate();
                console.log(params);
                this.$api.announce
                  .add(params)
                  .then(res => {
                    this.loading = false;
                    if (res.code == 200) {
                      this.$message.success("操作成功!");
                      this.showindex = true;
                      this.reload();
                    } else {
                      this.$message.error("操作失败!" + res.msg);
                    }
                  })
                  .catch(err => {
                    this.loading = false;
                    this.$message.error("操作失败!" + err);
                  });
              })
              .catch(() => {
                return;
              });
          }
        });
      }
    },
    onCancel() {
      this.$refs.announceForm.resetFields();
      this.showindex = true;
    },

    getNowFormatDate() {
      var date = new Date();
      var seperator1 = "-";
      var seperator2 = ":";
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      var strHour = date.getHours();
      var strMiniute = date.getMinutes();
      var strSecond = date.getSeconds();

      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }

      if (strHour >= 0 && strHour <= 9) {
        strHour = "0" + strHour;
      }

      if (strMiniute >= 0 && strMiniute <= 9) {
        strMiniute = "0" + strMiniute;
      }

      if (strSecond >= 0 && strSecond <= 9) {
        strSecond = "0" + strSecond;
      }

      var currentdate =
        year +
        seperator1 +
        month +
        seperator1 +
        strDate +
        " " +
        strHour +
        seperator2 +
        strMiniute +
        seperator2 +
        strSecond;
      return currentdate;
    }
  },

  extendCopy(b) {
    var a = {};
    for (var i in b) {
      a[i] = b[i];
    }
    return a;
  }
};
</script>

<style lang="less" scoped>
.col-flex {
  padding-top: 30px;
  height: 100%;
  box-sizing: border-box;
  .breadcrumb-container {
    height: 30px;
    margin-top: -20px;
  }
  .maincont-container {
    height: calc(~"100% - 10px");
    margin-top: 3px;

    .data-form {
      padding: 0px 150px;

      .el-select {
        display: block;
      }

      .upload-demo {
        text-align: left;
      }
    }
  }
}
</style>